package edu.cuit.avatar;

import java.io.*;

/**
 * BufferedInputStream/BufferedOutputStream
 *      可以通过减少磁盘读写次数来提高输入输出的效率。
 *      使用BufferedInputStream时磁盘上的一整块数据一次性的读入到内存的缓冲区中
 *      使用BufferedOutputStream时,数据先写入到内存的缓冲区，当缓冲区已满或者关闭时，将缓冲区中的数据一次性写入到磁盘中
 *
 * BufferedReader/BufferedWriter
 *
 *
 * 应该总是使用缓冲区I/O来加速读写
 *
 * @author <a href="mailto:1020zhaodan@163.com">赵因斯坦</a>
 * @version 1.0
 * @date 2025/7/12 10:10
 */
public class BufferedStreamDemo {
    public static void copy(File source, File dest){
        try(var input = new BufferedInputStream(new FileInputStream(source));
            var output = new BufferedOutputStream(new FileOutputStream(dest))){
            byte[] buffer = new byte[1024 * 8];
            int len = -1;
            //从BufferedInputStream的缓冲区中加载数据到buffer数组中
            while((len = input.read(buffer)) != -1){
                //将读取到的数据写入到输出流中
                output.write(buffer, 0, len);
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        var source = new File("D:/avatar/5.gif");
        var dest = new File("5.gif");

        //copy(source, dest);
        readByBufferedReader();
    }

    public static void readByBufferedReader(){
        try(var input = new BufferedReader(new FileReader("D:/chapter1.txt"))){
            String line = null;
            while((line = input.readLine()) != null){
                System.out.println(line);
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void writeByBufferedReader(){
        try(var output = new PrintWriter(new BufferedWriter(new FileWriter("test.log")))){

        } catch (IOException e){
            e.printStackTrace();
        }
    }
}
